package com.liuke.question4.handler;

import java.io.*;

/**
 * @Auther: 刘科
 * @Date: 2021/07/04/10:28
 * @Description:
 */
public abstract class AbstractPipeHandler implements Runnable {

    private PipedInputStream inputStream;

    private PipedOutputStream outputStream;

    public AbstractPipeHandler(PipedInputStream inputStream, PipedOutputStream outputStream) {
        this.inputStream = inputStream;
        this.outputStream = outputStream;
    }

    protected abstract void handle(BufferedReader reader);


    protected void writeToStream(String out) {
        if (out.length() == 0) return;

        try {
            outputStream.write(out.getBytes());
            outputStream.write("\n".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected void closeOutStream() {
        try {
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        handle(reader);
    }
}
